# Create your views here.
import re

from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from demo.demo_logging_mgmt.models import UserActionLog
from demo.demo_logging_mgmt.serializers import UserActionLogSerializer
from demo_common_module.utils.exception_type import Exception400
from demo_common_module.utils.result_utils import ResultUtils
from demo_common_module.utils.time_utils import str_to_datetime


class UserActionLogApiView(APIView):
    """获取用户操作日志"""
    page = openapi.Parameter("page", openapi.IN_QUERY, description="页码",
                             type=openapi.TYPE_INTEGER, required=False)

    n = openapi.Parameter("n", openapi.IN_QUERY, description="条数",
                          type=openapi.TYPE_INTEGER, required=False)

    user_name = openapi.Parameter("user_name", openapi.IN_QUERY, description="用户名",
                                  type=openapi.TYPE_INTEGER, required=False)

    start_time = openapi.Parameter("start_time", openapi.IN_QUERY, description="开始时间，格式为：%Y-%m-%d",
                                   type=openapi.TYPE_STRING, required=True)

    end_time = openapi.Parameter("end_time", openapi.IN_QUERY, description="结束时间，格式为：%Y-%m-%d",
                                 type=openapi.TYPE_STRING, required=True)

    @swagger_auto_schema(
        operation_description="查看用户行为日志",
        responses={200: "success"},
        manual_parameters=[start_time, end_time, user_name, page, n]
    )
    def get(self, request):
        start_time = request.query_params.get("start_time")
        end_time = request.query_params.get("end_time")
        user_name = request.query_params.get("user_name")
        page = int(request.query_params.get("page", 1))
        n = int(request.query_params.get("n", 10))

        if not all([start_time, end_time]):
            raise Exception400("缺少参数")

        pattern = re.compile('^\d{4}-\d{2}-\d{2}$')
        if (not pattern.match(start_time)) or (not pattern.match(end_time)):
            raise Exception400('时间格式不对')

        query_condition = dict()
        start_time = start_time + " " + "00:00:00"
        start_time = str_to_datetime(start_time)
        end_time = end_time + " " + "23:59:59"
        end_time = str_to_datetime(end_time)
        query_condition["create_time__gte"] = start_time
        query_condition["create_time__lte"] = end_time
        if user_name:
            query_condition["user_name__icontains"] = user_name

        total = UserActionLog.objects.filter(**query_condition).count()
        user_action_objs = UserActionLog.objects.filter(**query_condition).order_by("-create_time")[
                           (page - 1) * n: page * n]

        serializer = UserActionLogSerializer(user_action_objs, many=True)

        ResultUtils.process_result(serializer.data)

        return Response({"status": "success", "message": "Query Success", "data": serializer.data, "total": total},
                        status=status.HTTP_200_OK)
